#!/bin/bash

# This script is used to regenerate Makefile.dep using a sequence
# like this:
#
# $ ./configure
# $ make CFLAGS=-MMD
# $ gendep > Makefile.dep


mk_dep_list ()
{
	local line
	local f

	while read line ; do
		line=${line/:/}

		for f in $line ; do
			echo "$f"
		done
	done
}

mk_dep_sort ()
{
	local tgt src

	read tgt
	read src

	echo "$tgt"
	echo "$src"

	sort -u
}

mk_dep_rule ()
{
	local tgt src

	read tgt
	read src

	printf "%s: %s" "$tgt" "$src"

	while read src ; do
		printf " \\\\\\n"
		printf "\\t%s" "$src"
	done

	printf "\\n"
}

mk_dep ()
{
	local src=$1

	cat "$src" |\
	mk_dep_list |\
	grep "^src/" |\
	mk_dep_sort |\
	mk_dep_rule
}

echo "# Makefile.dep"
echo "#"
echo "# This file was generated by gendep"

find . -type f -name "*.d" |\
sort |\
while read src ; do
	echo
	mk_dep "$src"
done
